﻿(function () {
    $.fn.ch2Dialog = function (options) {
        var defaults = {
            show: true,
            width: false,
            remote: false,
            content: '',
            title: '提示信息',
            iconClassName: '',
            tips: '',
            modal: false,
            buttons: [
                {
                    text: '确认',
                    className: 'u-btn-blue',
                    iconClassName: 'fa-check-circle',
                    handler: function (b, m) {
                        m.show(false);
                    }
                }
            ],
            onHide: function (m) { },
            onShow: function (m) { },
            onLoad: function (m) { }
        };
        $.extend(defaults, options);
        var $_dialog = $(this);
        var elmId = '_' + (Math.random() + '').replace('.', '');
        if (!$_dialog) {
            $('<div id="' + elmId + '"></div>').appendTo('body');
            $_dialog = $('#' + elmId);
        } else {
            if (!$_dialog.prop('id')) {
                $_dialog.prop('id', elmId);
            } else {
                elmId = $_dialog.prop('id');
            }
        }
        var _dialogHtml = '<div class="lymask"></div>';
        _dialogHtml += '<table class="lytable"><tbody><tr><td class="lytd">';
        _dialogHtml += '<div class="lywrap">';
        _dialogHtml += '<div class="lytt"><h2 class="u-tt"></h2><span class="lyclose">&times;</span></div>';
        _dialogHtml += '<div class="lyct"></div>';
        _dialogHtml += '<div class="lybt">';
        _dialogHtml += '<div class="lyother"><p></p></div>';
        _dialogHtml += '<div class="lybtns"></div>';
        _dialogHtml += '</div></div></td></tr></tbody></table>';
        if ((!defaults.remote) && (!defaults.content)) {
            defaults.content = $_dialog.html();
        }
        $_dialog.html(_dialogHtml);
        $_dialog.addClass('m-layer');
        var dragging = false;
        var iX, iY;
        $_dialog.on('mousedown', '.lytt', function (e) {
            dragging = true;
            var oL = 0;
            var oT = 0;
            if ($_dialog.find('.lywrap').css('left')!='auto') {
                oL = parseInt($_dialog.find('.lywrap').css('left'));
            } else {
                oL = this.offsetLeft;
            }
            if ($_dialog.find('.lywrap').css('top') != 'auto') {
                oT = parseInt($_dialog.find('.lywrap').css('top'));
            } else {
                oT = this.offsetTop;
            }
            iX = e.clientX - oL;
            iY = e.clientY - oT;
            document.getElementById(elmId).setCapture && document.getElementById(elmId).setCapture();
            return false;
        });
        $_dialog.on('mousemove', '.lytt', function (e) {
            if (dragging) {
                var e = e || window.event;
                var oX = e.clientX - iX;
                var oY = e.clientY - iY;
                $_dialog.find('.lywrap').css({ "left": oX + "px", "top": oY + "px" });
                return false;
            }
        });
        $(document).mouseup(function (e) {
            dragging = false;
            document.getElementById(elmId).releaseCapture && document.releaseCapture();
            e.cancelBubble = true;
        });

        //function
        var _destroy = function () {
            $($_dialog.selector).remove();
        };
        var _show = function (trueORfalse) {
            if (trueORfalse === false) {
                $_dialog.removeClass('m-layer-show');
                if ('undefined' == typeof (document.body.style.maxHeight)) {
                    $('select').removeClass('dialogshow');
                }
                defaults.onHide(resultObject);
            } else {
                //resultObject
                //for ie6
                if ('undefined' == typeof (document.body.style.maxHeight)) {
                    var _bodyHeight = $('body').height();
                    var _bodyWidth = $('body').width();
                    $_dialog.height(_bodyHeight).width(_bodyWidth);
                    $_dialog.find('.lymask').height(_bodyHeight).width(_bodyWidth);
                    $('select').addClass('dialogshow');
                }
                //for ie6 end
                $_dialog.addClass('m-layer-show');
                if ($_dialog.attr('data-loaded') == 'true') {
                    _loadContent(defaults.remote, defaults.content);
                }
                defaults.onShow(resultObject);
            }
        };
        _show(defaults.show);


        var _setTitle = function (text, iconClassName) {
            $_dialog.find('.lytt h2').html((iconClassName ? '<i class="fa ' + iconClassName + '"></i>' : '') + '<span>' + text + '</span>');
        };
        _setTitle(defaults.title, defaults.iconClassName);

        var _setTips = function (text) {
            $_dialog.find('.lyother p').text(text);
        };
        _setTips(defaults.tips);

        var _defButtons = function (btns) {
            $.each(btns, function (index, elm) {
                var _btnHtml = '<button type="button" data-btnid="btn-' + index + '" class="u-btn ' + elm.className + '"><i class="fa ' + elm.iconClassName + '"></i>' + elm.text + '</button>';
                $_dialog.find('.lybtns').append(_btnHtml);
            });
            $.each(btns, function (index, elm) {
                $($_dialog.selector + ' [data-btnid="btn-' + index + '"]').on('click', function () {
                    elm.handler($(this), resultObject);
                });
            });
        };
        _defButtons(defaults.buttons);

        var _setWidth = function (width) {
            if (width) {
                $_dialog.find('.lywrap').css({ 'width': width + 'px' });
            }
        };
        _setWidth(defaults.width);

        var _loadContent = function (remote, content) {
            if (remote) {
                $_dialog.find('.lyct').html('<p><i class="fa fa-refresh"></i>正在加载...<p>')
                    .load((remote + '').indexOf('?') < 0 ? remote + '?____t=' + Math.random() : remote + '&____t=' + Math.random(), function (_html, _state) {
                        if (_state != 'success') {
                            $_dialog.find('.lyct').html('<p><i class="fa fa-meh-o"></i>加载失败!</p>');
                        }
                    });
            } else {
                $_dialog.find('.lyct').html(content);
            }
            $_dialog.attr('data-loaded', 'true');
            defaults.onLoad(resultObject);
        };
        _loadContent(defaults.remote, defaults.content);

        var _lockedBtn = function (btnindex, trueORfalse) {
            if (trueORfalse === false) {
                $_dialog.find('[data-btnid="btn-' + btnindex + '"]').prop('disabled', false);
            } else {
                $_dialog.find('[data-btnid="btn-' + btnindex + '"]').prop('disabled', true);
            }
        };

        var _setModal = function (trueORfalse) {
            if (trueORfalse === false) {
                if ($_dialog.find('.lymask').length) {
                    var $lymask = $_dialog.find('.lymask');
                    $lymask.remove();
                }
            } else {
                if (!$_dialog.find('.lymask').length) {
                    $_dialog.append('<div class="lymask"></div>');
                }
            }
        };
        _setModal(defaults.modal);
        $($_dialog.selector + ' .lyclose').on('click', function () {
            _show(false);
        });
        var resultObject = {
            elm: $_dialog,
            show: function (trueORfalse) { _show(trueORfalse); return this; },
            setTitle: function (text, iconClassName) { _setTitle(text, iconClassName); return this; },
            setTips: function (text) { _setTips(text); return this; },
            setWidth: function (width) { _setWidth(width); return this; },
            lockedBtn: function (btnindex, trueORfalse) { _lockedBtn(btnindex, trueORfalse); return this; },
            loadContent: function (remote, content) { _loadContent(remote, content); return this; },
            setModal: function (trueORfalse) { _setModal(trueORfalse); return this; },
            destroy: function () {
                _destroy();
            }
        };
        return resultObject;
    };
})(jQuery);
jQuery.ch2Alert = function (message, title, onClose) {
    if (!title) {
        title = "提示信息";
    }
    if (!onClose) {
        onClose = function () { };
    }
    var index = $('[id^="ch2alert-"]').length;
    var $alertHtml = '<div id="ch2alert-' + index + '"></div>';
    $('body').append($alertHtml);
    $ch2alert = $('#ch2alert-' + index).ch2Dialog({
        modal: true,
        show: true,
        title: title,
        remote: false,
        content: '<p>' + message + '<p>',
        iconClass: 'fa-info-circle',
        buttons: [
            {
                text: '确认',
                iconClassName: 'fa-check',
                className: 'u-btn-green',
                handler: function (b, m) {
                    m.show(false);
                }
            }
        ],
        onHide: onClose
    });
};
jQuery.ch2Confirm = function (message, title, func) {
    if (!title) {
        title = '确认信息';
    }
    if (typeof title == 'function') {
        func = title;
        title = '确认信息';
    }
    var index = $('[id^="ch2confirm-"]').length;
    var $alertHtml = '<div id="ch2confirm-' + index + '"></div>';
    $('body').append($alertHtml);
    $ch2confirm = $('#ch2confirm-' + index).ch2Dialog({
        modal: true,
        show: true,
        title: title,
        remote: false,
        content: '<p>' + message + '<p>',
        iconClass: 'fa-info-circle',
        buttons: [
            {
                text: '确认',
                iconClassName: 'fa-check',
                className: 'u-btn-green',
                handler: function (b, m) {
                    func(b, m);
                }
            }, {
                text: '取消',
                iconClassName: 'fa-times-circle',
                className: 'u-btn-yellow',
                handler: function (b, m) {
                    m.show(false);
                }
            }
        ]
    });
};
jQuery.ch2Info = function (message, buttons) {
    var index = $('[id^="ch2alert-"]').length;
    var $alertHtml = '<div id="ch2alert-' + index + '"></div>';
    $('body').append($alertHtml);
    $ch2alert = $('#ch2alert-' + index).ch2Dialog({
        modal: true,
        show: true,
        title: '提示信息',
        remote: false,
        content: '<p>' + message + '<p>',
        iconClass: 'fa-info-circle',
        buttons: buttons
    });
};